﻿// Sequin.FrequencyCounter
//
// (c) 2011 Arthur Pitman
//
// Part of the Sequin Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License (Version 2.1) as published by the Free Software Foundation.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License (Version 2.1) along with this library; if not, write to the 
// Free Software Foundation, Inc., 
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
// or see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Sequin
{
	/// <summary>
	/// Counts the frequency of items of a given type
	/// </summary>
	public class FrequencyCounter<T>
	{
		/// <summary>
		/// Stores frequency counts for a given type
		/// </summary>
		public Dictionary<T, int> Counts {get; protected set;}

		/// <summary>
		/// Initializes a new <see cref="FrequencyCounter&lt;T&gt;"/> instance
		/// </summary>
		public FrequencyCounter()
		{
			Counts = new Dictionary<T, int>();
		}

		/// <summary>
		/// Increments the count for the given item
		/// </summary>
		/// <param name="i">The item to increment</param>
		public void Increment(T i)
		{
			if (Counts.ContainsKey(i))
				Counts[i]++;
			else
				Counts.Add(i, 1);
		}

		/// <summary>
		/// Saves the counts as a list ordered by frequency
		/// </summary>
		/// <param name="filename">The filename</param>
		public void SaveAs(string filename)
		{
			var sorted = from x in Counts
							orderby x.Value descending
							select x;
			var writer = File.CreateText(filename);
			foreach (var pair in sorted)
			{
				writer.WriteLine("{0}, {1}", pair.Value, pair.Key);
			}
			writer.Close();
		}
	}
}
